"""
数据库模型定义
"""
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Text, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from app.database import Base


class Work(Base):
    """
    作品表
    存储作品的基本信息
    """
    __tablename__ = "works"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String(200), nullable=False, comment="作品标题（英文）")
    subtitle = Column(String(200), nullable=False, comment="作品副标题（中文）")
    cover_image = Column(String(500), nullable=True, comment="封面图片URL")
    description = Column(Text, nullable=True, comment="作品描述")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    is_active = Column(Boolean, default=True, comment="是否启用")
    
    # 关联关系
    images = relationship("WorkImage", back_populates="work", cascade="all, delete-orphan")
    favorites = relationship("Favorite", back_populates="work", cascade="all, delete-orphan")


class WorkImage(Base):
    """
    作品图片表
    存储每个作品的多张图片
    """
    __tablename__ = "work_images"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False, comment="作品ID")
    image_url = Column(String(500), nullable=False, comment="图片URL")
    sort_order = Column(Integer, default=0, comment="排序顺序")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    
    # 关联关系
    work = relationship("Work", back_populates="images")


class User(Base):
    """
    用户表
    存储小程序用户信息
    """
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    openid = Column(String(100), unique=True, nullable=False, index=True, comment="微信openid")
    nickname = Column(String(100), nullable=True, comment="用户昵称")
    avatar = Column(String(500), nullable=True, comment="用户头像URL")
    created_at = Column(DateTime, default=datetime.now, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    # 关联关系
    favorites = relationship("Favorite", back_populates="user", cascade="all, delete-orphan")


class Favorite(Base):
    """
    收藏表
    存储用户的收藏记录
    """
    __tablename__ = "favorites"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    work_id = Column(Integer, ForeignKey("works.id"), nullable=False, comment="作品ID")
    created_at = Column(DateTime, default=datetime.now, comment="收藏时间")
    
    # 关联关系
    user = relationship("User", back_populates="favorites")
    work = relationship("Work", back_populates="favorites")
    
    # 唯一约束：一个用户不能重复收藏同一个作品
    __table_args__ = (
        {"comment": "收藏表"},
    )

